package com.laogao.service;

import ch.qos.logback.classic.spi.ILoggingEvent;
import ch.qos.logback.classic.spi.ThrowableProxyUtil;
import com.laogao.model.LogMessage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.ConcurrentLinkedDeque;

@Service
public class LogWebSocketService {

    private static SimpMessagingTemplate messagingTemplate;

    private static final int MAX_LOG_ENTRIES = 1000;
    private static final ConcurrentLinkedDeque<LogMessage> logCache = new ConcurrentLinkedDeque<>();

    @Autowired
    public LogWebSocketService(SimpMessagingTemplate template) {
        messagingTemplate = template;
    }

    /**
     * 广播日志消息，同时保存到缓存中
     */
    public static void broadcast(ILoggingEvent event) {
        if (messagingTemplate != null) {
            LogMessage msg = new LogMessage();
            msg.setTimestamp(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date(event.getTimeStamp())));
            msg.setLevel(event.getLevel().toString());
            msg.setLogger(event.getLoggerName());
            msg.setMessage(event.getFormattedMessage());
            if (event.getThrowableProxy() != null) {
                String stackTrace = ThrowableProxyUtil.asString(event.getThrowableProxy());
                msg.setException(stackTrace);
            }
            addToCache(msg);
            messagingTemplate.convertAndSend("/topic/logs", msg);
        }
    }

    private static void addToCache(LogMessage msg) {
        synchronized (logCache) {
            if (logCache.size() >= MAX_LOG_ENTRIES) {
                logCache.pollFirst();
            }
            logCache.addLast(msg);
        }
    }

    /**
     * 用于查询当前缓存的日志
     */
    public static ConcurrentLinkedDeque<LogMessage> getLogCache() {
        return logCache;
    }
}
